import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
import { useUserStore } from './user'
import { getNewCartListApi, insertCartApi, delCartListApi } from '../apis/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    // state
    let cartList = ref([])
    // 如果有token，走接口购物车，没有token，走本地购物车
    const isLogin = computed(() => userStore.userInfo.token)
    // action
    // 获取新的购物车列表（接口购物车）
    const updateCartList = async () => {
        const res = await getNewCartListApi()
        cartList.value = res.data.result
    }
    // 添加购物车
    const addCart = async (good) => {
        const { skuId, count } = good
        if (isLogin.value) {
            await insertCartApi({ skuId, count })
            updateCartList()
        } else {
            // 添加购物车业务逻辑
            // 添加过该商品，直接加count；未添加过该商品，直接push
            const item = cartList.value.find(item => item.skuId === skuId)
            if (item) {
                item.count += count
            } else {
                cartList.value.push(good)
            }
        }
    }
    // 删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartListApi([skuId])
            updateCartList()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }
    }
    // 退出登录后，清空购物车数据
    const clearCart = () => {
        cartList.value = []
    }
    // 切换购物车选中状态
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find(item => item.skuId === skuId)
        item.selected = selected
    }
    // 切换全选
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }

    // 计算属性
    // 购物车商品总数量
    const totalCount = computed(() => {
        return cartList.value.reduce((a, c) => a + c.count, 0)
    })
    // 购物车商品总价
    const totalPrice = computed(() => {
        return cartList.value.reduce((a, c) => a + (c.count * c.price), 0)
    })
    // 全选功能
    const isAll = computed(() => {
        return cartList.value.every(item => item.selected === true)
    })
    // 购物车已选商品数量
    const checkedCount = computed(() => {
        return cartList.value.filter(item => item.selected === true).reduce((a, c) => a + c.count, 0)
    })
    // 购物车已选商品总价
    const checkedPrice = computed(() => {
        return cartList.value.filter(item => item.selected === true).reduce((a, c) => a + (c.count * c.price), 0)
    })

    return {
        cartList,
        addCart,
        delCart,
        updateCartList,
        clearCart,
        singleCheck,
        allCheck,
        totalCount,
        totalPrice,
        isAll,
        checkedCount,
        checkedPrice
    }
}, {
    persist: true
})